<?php
/*sql update :
 * ALTER TABLE `users` ADD `salt` VARCHAR( 10 ) NOT NULL AFTER `password` ;
 * ALTER TABLE `users` CHANGE `ip` `last_ip` VARCHAR( 40 ) NULL DEFAULT NULL;
*/

class User extends AppModel {

	var $name = 'User';

	var $validate = array(
		'username' => array(
						array('rule' => array('between', 5, 20), 'message' => 'Username should be between 5 & 20 characters.'),
						array('rule' => array('_isUnique', 'username'), 'message' => 'Username already used')
						),
		'password' => array('rule' => array('between', 5, 40), 'message' => 'Password should be between 5 & 32 characters.'),
		'email' => array(
				array('rule' => 'email', 'message' => 'Valid email required.'),
				array('rule' => array('_isUnique', 'email'), 'message' => 'Email already used.')
				)
		);
		//validates uniqueness of username and email only on register
		
		//'website' => '/^(http|https):\/\/(([A-Z0-9][A-Z0-9_-]*)(\.[A-Z0-9][A-Z0-9_-]*)+)(:(\d+))?\//i'
	
	/*var $hasOne = array('Customer' => array(
							'className' => 'Customer',
							'conditions' => '',
							'order' => '',
							'dependent' => false,
							'foreignKey' => 'user_id'
							)
						);
		*/				
	var $hasMany = array('Page' => array(
									'className' => 'Page',
									'conditions' => '',
									'order' => '',
									'foreignKey' => 'user_id'
									)
								);
	
	function validates(){
		if(!isset($this->data['User']['id'])){
			$this->new_user();
		}else{
			$this->edit_user();
		}
        return count($this->invalidFields()) == 0;
	}
	
	function select_users(){
		$select_users = array();
		$users = $this->findAll();
		foreach($users as $user){
			$select_users += array($user['User']['id'] => $user['User']['username']);
		}
		return $select_users;
	}
	
	//My validates
	function new_user(){
		$this->check_passwords();
	}
	
	function edit_user(){
		if(empty($this->data['User']['password'])){
			//don't change passwd	
			unset($this->data['User']['password']);
			unset($this->data['User']['password2']);
		}else{
			$this->check_passwords();
		}
	}
	
	//private
	
	function check_passwords(){
		if(!preg_match('/^.{5,40}$/', $this->data['User']['password'])){
			$this->invalidate('password', 'password must be between 5 & 40 characters');
		}elseif($this->data['User']['password'] != $this->data['User']['password2']){
			//passwords are different
			$this->invalidate('password2', 'password check failed');
		}else{
			//It's ok : new passwords & new salt
			$this->data['User']['salt'] = rand(99,9999999999);
			$clr_pass = $this->data['User']['password'];
			$this->data['User']['password'] = x_hashstr($this->data['User']['password'], $this->data['User']['salt']);	
		}
	}
	
}
?>
